

#pragma once

#include "stdint.h"

#define MSG_ANSWER_SIZE 15

#define ID_LEN (10)
#define MSG_BEGIN TEXT('\xf9')
#define MSG_TRANSFERRED TEXT('\xf8')

#define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0]))

#define LIST_ITEM_MAX 10000
#define LIST_ITEM_PERDELETE 1000

#include <map>
#include <set>
#include <vector>

using namespace std;

struct checkItem
{
	TCHAR id[16];
	uint64_t firstTime;
	uint64_t lastTime;

	unsigned count;
	unsigned errCount;

	int electricity;
	int nindex;
	checkItem(){
		memset(this, 0, sizeof(*this));
	}
};

struct answerItem
{
	TCHAR id[16];
	TCHAR answer[16];
	uint64_t time;
	int electricity;
	int nindex;
	answerItem(){
		nindex = 0;
		time = 0;
		electricity = 0;
		memset(id, 0, sizeof(id));
		memset(answer, 0, sizeof(answer));
	}
};

struct readThreadData
{
	volatile long runing;
	volatile long exit;

	HWND hWnd;
	HANDLE hCom;
	CWinThread* thread;

	bool isCH9326;
	unsigned inportlen;
	unsigned outportlen;

	CWinThread* threadReal;
	HWND m_hMainWnd;
};

unsigned chrVal(TCHAR c);
unsigned chrMask();

#define USB_VID 0x1A86
#define USB_PID 0xE010

typedef void (msgBufferFn)(int type, const char *buf, unsigned len, void *arg);

class msgBuffer
{
public:
	msgBuffer(HWND hWnd = 0, unsigned size = 2048);
	~msgBuffer();

	bool addInput(char *buf, unsigned len);
	void SetMainWnd(HWND hWnd){m_hMainWnd = hWnd;};
	void SetFn(msgBufferFn *fn, void *arg){m_fn = fn; m_arg = arg;};
protected:
	unsigned getMsg();
	int getMsgOne(char *buf, unsigned len);
	char* getMsgStart(char *buf, unsigned len);
	int processMsg(char *start, unsigned size, unsigned len);
private:
	char *m_buf;
	unsigned m_size;
	unsigned m_len;
	HWND m_hMainWnd;

	msgBufferFn *m_fn;
	void *m_arg;
};

class anwerOnoff
{
public:
	anwerOnoff();
	void on(const CString &id);
	void off(const CString &id);

	void onAll();
	void offAll();

	bool arrowOff(const CString &id);
private:
	CMutex m_mutex;
	static const bool  m_allOff;
	map <CString, bool> m_anwerOnoff;
};

unsigned char HIDSpeed(unsigned speed);
void msgXData(CString &str, TCHAR *in, unsigned len);
void idTrans(const TCHAR *in, TCHAR *out);
void elecTrans(int e, TCHAR *in);

#define TIME_FORMAT (TEXT("%Y-%m-%d %X"))

int toLocalCode(const char *in, unsigned inlen, TCHAR *out, unsigned outlen);
int toUtf8(TCHAR *in, unsigned inlen, const char *out, unsigned outlen);
bool isSystemType();

void readFileString(CString filePath, set<CString> &s);
void writeFileString(CString filePath, set<CString> &s);

bool arrowOff(const CString &id);
void anwerOn(const CString &id);
void anwerOff(const CString &id);
void anwerOnAll();
void anwerOffAll();

int timeEchoMsg(TCHAR *buf, unsigned size);
